import json
from datetime import date

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from haystack.views import SearchView

from apps.contents.models import ContentCategory
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from utils.goods import get_categories, get_breadcrumb, get_goods_specs
from utils.viewmixin import LoginMixin


# class IndexView(View):
#     def get(self, request):
#         # 获取商品类别数据
#         categories = get_categories()
#         # 存放广告数据的字典
#         contents = {}
#         # 查询出所有广告
#         content_categories = ContentCategory.objects.all()
#         # 遍历广告数据存入字典   类别键为key  value为可以展示的广告数据
#         for cat in content_categories:
#             contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
#         # 组织前端需要的json数据格式
#
#         context = {
#             'categories': categories,
#             'contents': contents
#         }
#         # 返回模板  和  模板内需要的数据
#         return render(request, 'index.html', context)


# /list/115/skus/?page=1&page_size=5&ordering=-create_time
class ListView(View):
    def get(self, request, category_id):
        # 获取前端数据  页数 一页几条数据 排序方式
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        # 查询分类对象
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '分类查询失败'})
        # 获取三级分类的名字
        breadcrumb = get_breadcrumb(category)
        # 查询分类对象下的所有商家的商品数据
        try:
            skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '查询商品失败'})
        # 分页
        paginator = Paginator(skus, page_size)
        page_skus = paginator.page(page)
        # 组织数据
        sku_list = []
        for sku in page_skus:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url if sku.default_image else "",
            })
        # count为总页数
        count = paginator.num_pages
        # 返回数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'breadcrumb': breadcrumb, 'list': sku_list, 'count': count})


# http://www.meiduo.site:8800/hot/115/
class HotGoodsView(View):
    def get(self, request, category_id):
        """
        查询销量排行
        :param request:
        :param category_id: 分类id
        :return: 返回json数据状态和销量排行的商品数据
        """
        try:
            # 根据分类id查询分类对象
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '分类查询失败'})
        try:
            # 根据分类对象查询商品数据 按销量排序 倒序
            skus = SKU.objects.filter(category=category, is_launched=True).order_by('-sales')
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '查询商品失败'})
        # count = 1
        # hot_sku_list = []
        # for sku in skus:
        #     if count == 10:
        #         break
        #     hot_sku_list.append({
        #         'id': sku.id,
        #         'name': sku.name,
        #         'price': sku.price,
        #         'default_image_url': sku.default_image.url,
        #     })
        #     count += 1
        try:
            hot_sku_list = [
                {
                    'id': skus[0].id,
                    'name': skus[0].name,
                    'price': skus[0].price,
                    'default_image_url': skus[0].default_image.url if skus[0].default_image else "",
                },
                {
                    'id': skus[1].id,
                    'name': skus[1].name,
                    'price': skus[1].price,
                    'default_image_url': skus[1].default_image.url if skus[1].default_image else "",
                }
            ]
        except Exception as e:
            print(e)
            hot_sku_list = []

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'hot_skus': hot_sku_list})


class MySearchView(SearchView):
    def create_response(self):
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url if sku.object.default_image else "",
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count,
            })

        return JsonResponse(data_list, safe=False)


# class DetailView(View):
#     def get(self, request, sku_id):
#         try:
#             sku = SKU.objects.get(id=sku_id)
#         except SKU.DoesNotExist:
#             return render(request, '404.html')
#
#         categories = get_categories()
#         breadcrumb = get_breadcrumb(sku.category)
#         specs = get_goods_specs(sku)
#
#         context = {
#             'categories': categories,
#             'breadcrumb': breadcrumb,
#             'sku': sku,
#             'specs': specs,
#         }
#
#         return render(request, 'detail.html', context)


# http://www.meiduo.site:8800/detail/visit/115/
class CategoryVisitCountView(View):
    def post(self, request, category_id):
        # 校验参数 分类id是否正确
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        # 获取到今天时间  以便获取今天的数据
        today = date.today()
        # 查询出数据库内该分类id关联的计数数量，并且是今天的计数
        try:
            goods_visit_count = GoodsVisitCount.objects.get(category=category, date=today)
        # 如果没有查询到 就说明今天该分类还没有人访问 就新创建一个数据对象
        except:
            goods_visit_count = GoodsVisitCount()

        # 写入数据   计数数量+1  时间是今天  分类id为该分类id
        try:
            goods_visit_count.count += 1
            goods_visit_count.date = today
            goods_visit_count.category_id = category_id

            # 保存到数据库
            goods_visit_count.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '保存失败'})
        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


# http://www.meiduo.site:8800/browse_histories/
class UserBrowseHistory(LoginMixin, View):
    def post(self, request):
        user = request.user
        # 获取到前端传来的数据  商品id
        json_data = json.loads(request.body)
        sku_id = json_data.get('sku_id')
        # 校验参数  是否真实存在该商品
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        # 连接redis
        redis_conn = get_redis_connection('history')
        # 创建管道
        pl = redis_conn.pipeline()
        # 去除重复的浏览记录
        pl.lrem('history_%s' % user.id, 0, sku_id)
        # 在最左边添加最新的浏览记录
        pl.lpush('history_%s' % user.id, sku_id)
        # 只存入5条数据
        pl.ltrim('history_%s' % user.id, 0, 4)
        # 提交操作
        pl.execute()

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

    def get(self, request):
        # 检测用户是否登录
        user = request.user
        # 连接redis
        redis_conn = get_redis_connection('history')
        # 查询出redis内所有浏览记录数据
        sku_ids = redis_conn.lrange('history_%s' % user.id, 0, -1)
        # 组织前端需要的数据
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url if sku.default_image else "",
            }
            skus.append(sku_dict)
        # 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "skus": skus})
